<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>废旧金属物资回收业登记系统</title>
    <script src="js/vue.min.js"></script>
    <script src="js/axios.min.js"></script>
    <link rel="stylesheet" href="css/index.css" />
</head>

<body>
    <div id="app">
        <div class="container">
            <!-- 页面标题 -->
            <div class="header">
                <div class="header-title">
                    <h1>收购站点：<span>{{formData.collectionName}}</span></h1>
                </div>
                <div class="header-content">
                    <div class="header-content-item-title">
                        <span class="tip-content">
                            <img src="img/icon_1.png" alt="">
                            <span class="tip-text">温馨提示：尊敬的废旧物资收购站负责人</span>
                        </span>
                        <span class="more-link" @click="showMoreModalfun">更多<img src="img/icon_mo.png" style="width: 8px;height: 12px;vertical-align: -1px;margin-left:5px;margin-right: 0;" alt=""></span>
                    </div>
                </div>

            </div>

            <!-- 上报信息表单 -->
            <div class="form-section">


                <form @submit.prevent="submitForm">
                    <div class="form-box">
                        <div class="form-title">上报信息</div>
                        <!-- 销售人员姓名 -->
                        <div class="form-row">
                            <label class="form-label">销售人员姓名</label>
                            <input type="text" class="form-input" v-model="formData.marketName" placeholder="销售人员姓名">
                        </div>

                        <!-- 销售人员手机号 -->
                        <div class="form-row">
                            <label class="form-label">销售人员手机号</label>
                            <input type="tel" class="form-input" v-model="formData.phone" placeholder="(选填)">
                        </div>

                        <!-- 身份证号码 -->
                        <div class="form-row">
                            <label class="form-label">身份证号码</label>
                            <input type="text" class="form-input" v-model="formData.idCard" placeholder="(选填)">
                        </div>

                        <!-- 收购金额 -->
                        <div class="form-row">
                            <label class="form-label required">收购金额</label>
                            <input type="number" class="form-input" v-model="formData.amount" placeholder="(必填)" required>
                            <label class="required-text">元</label>
                        </div>
                    </div>

                    <!-- 销售人员照片 -->
                    <div class="form-group">
                        <div class="form-title">销售人员照片</div>
                        <div class="photo-upload-container">
                            <div class="photo-upload" :class="{ 'has-photo': formData.marketPhoto }" @click="openNativeCamera('salesperson')">
                                <div v-if="!formData.marketPhoto">
                                    <img src="img/icon_upload.png" alt="">
                                </div>
                                <img v-else :src="formData.marketPhoto" class="photo-preview" alt="销售人员照片">
                            </div>
                            <div class="photo-instructions" v-if="!formData.marketPhoto">全身照、面部照片（必填）</div>
                            <div v-else class="photo-instructions success-message">✓ 照片已拍摄</div>
                        </div>

                        <!-- 隐藏的文件输入 -->
                        <input type="file" id="camera-input-salesperson" accept="image/*" capture="environment" style="display: none;" @change="handlePhotoCapture('salesperson', $event)">

                    </div>

                    <!-- 收购物资照片 -->
                    <div class="form-group">
                        <div class="form-title">收购物资图片</div>
                        <div class="photo-upload-container">
                            <div class="photo-upload" :class="{ 'has-photo': formData.collectionPhoto }" @click="openNativeCamera('material')">
                                <div v-if="!formData.collectionPhoto">
                                    <img src="img/icon_upload.png" alt="">
                                </div>
                                <img v-else :src="formData.collectionPhoto" class="photo-preview" alt="收购物资照片">
                            </div>
                            <div v-if="!formData.collectionPhoto" class="photo-instructions">全身照片、细节照片 (必填)</div>
                            <div v-else class="success-message photo-instructions">✓ 照片已拍摄</div>
                        </div>

                        <!-- 隐藏的文件输入 -->
                        <input type="file" id="camera-input-material" accept="image/*" capture="environment" style="display: none;" @change="handlePhotoCapture('material', $event)">

                    </div>

                    <!-- 提交按钮 -->
                    <button type="submit" class="submit-btn" :disabled="!isFormValid">
                        确认无误提交
                    </button>
                </form>
            </div>
        </div>

        <!-- 自定义弹窗 -->
        <div class="custom-modal" v-if="showModal" @click="closeModal">
            <div class="modal-content" @click.stop>
                <div class="modal-header">
                    <div class="modal-icon" :class="modalType">
                        <span v-if="modalType === 'success'">✓</span>
                        <span v-else-if="modalType === 'error'">✕</span>
                        <span v-else>!</span>
                    </div>
                </div>
                <div class="modal-body">
                    <p>{{ modalMessage }}</p>
                </div>
                <div class="modal-footer">
                    <button class="modal-btn" @click="closeModal">确定</button>
                </div>
            </div>
        </div>

        <!-- 更多提示弹窗 -->
        <div class="custom-modal" v-if="showMoreModal" @click="closeMoreModal">
            <div class="modal-content" @click.stop>
                <div class="modal-body">
                    <h3 class="more-modal-title">温馨提示</h3>
                    <div class="more-modal-content">
                        <p>尊敬的废旧物资收购站负责人:</p>
                        <p>您好!为加强辖区废旧金属物资管理，防范和打击违法犯罪行为，请您在收购废旧金属物资时，务必严格落实以下要求:</p>
                        <p>1、及时上报:收购废旧金属(如电缆、电线、金属构件等)时，请详细登记出售人身份信息、物品来源及特征，并及时报备;</p>
                        <p>2、、禁止收购可疑物品:如发现物品来源不明、有拆盗痕迹或涉及公共设施(如井盖、护栏等)，请立即联系派出所;</p>
                        <p>3、配合执法检查:请妥善保存交易记录，配合公安机关日常检查。</p>
                        <p>感谢您的理解与支持!共同维护良好的治安环境，需要我们携手努力。</p>

                    </div>
                </div>
                <div class="modal-footer">
                    <button class="modal-btn" @click="closeMoreModal">我知道了</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        new Vue({
            el: '#app',
            data: {
                formData: {
                    collectionName: '沁水县豫飞商贸有限公司',
                    marketName: '',
                    phone: '',
                    idCard: '',
                    amount: '',
                    marketPhoto: '',
                    collectionPhoto: '',
                    companyId: ''
                },
                currentPhotoType: '',
                showModal: false,
                modalMessage: '',
                modalType: 'info',
                showMoreModal: false
            },
            computed: {
                isFormValid() {
                    return this.formData.amount &&
                        this.formData.marketPhoto &&
                        this.formData.collectionPhoto;
                }
            },
            mounted() {
                // 从URL参数中获取collectionName和companyId
                const urlParams = new URLSearchParams(window.location.search);
                this.formData.collectionName = urlParams.get('collectionName') || '沁水县豫飞商贸有限公司';
                this.formData.companyId = urlParams.get('companyId') || '';
            },
            methods: {
                // 显示弹窗
                showMessage(message, type = 'info') {
                    this.modalMessage = message;
                    this.modalType = type;
                    this.showModal = true;
                },

                // 关闭弹窗
                closeModal() {
                    this.showModal = false;
                },

                // 显示更多弹窗
                showMoreModalfun() {
                    this.showMoreModal = true;
                },

                // 关闭更多弹窗
                closeMoreModal() {
                    this.showMoreModal = false;
                },

                // 打开原生相机
                openNativeCamera(type) {
                    this.currentPhotoType = type;
                    const inputId = type === 'salesperson' ? 'camera-input-salesperson' : 'camera-input-material';
                    const input = document.getElementById(inputId);
                    input.click();
                },

                // 处理照片拍摄
                handlePhotoCapture(type, event) {
                    const file = event.target.files[0];
                    if (file) {
                        // 将文件转换为base64格式
                        const reader = new FileReader();
                        reader.onload = (e) => {
                            if (type === 'salesperson') {
                                this.formData.marketPhoto = e.target.result;
                            } else {
                                this.formData.collectionPhoto = e.target.result;
                            }
                        };
                        reader.readAsDataURL(file);
                    }

                    // 重置input，允许重复选择同一文件
                    event.target.value = '';
                },

                // 提交表单
                async submitForm() {
                    if (!this.isFormValid) {
                        this.showMessage('请完善必填信息', 'error');
                        return;
                    }

                    try {
                        // 创建FormData对象
                        const formData = new FormData();

                        // 添加表单字段
                        formData.append('collectionName', this.formData.collectionName);
                        formData.append('companyId', this.formData.companyId || '');
                        formData.append('marketName', this.formData.marketName || '');
                        formData.append('phone', this.formData.phone || '');
                        formData.append('idCard', this.formData.idCard || '');
                        formData.append('amount', this.formData.amount);

                        // 处理销售人员照片
                        if (this.formData.marketPhoto) {
                            // 将base64转换为Blob
                            const marketPhotoBlob = this.base64ToBlob(this.formData.marketPhoto);
                            formData.append('marketPhoto', marketPhotoBlob, 'market_photo.jpg');
                        }

                        // 处理收购物资照片
                        if (this.formData.collectionPhoto) {
                            // 将base64转换为Blob
                            const collectionPhotoBlob = this.base64ToBlob(this.formData.collectionPhoto);
                            formData.append('collectionPhoto', collectionPhotoBlob, 'collection_photo.jpg');
                        }

                        console.log('提交数据到API:', formData);

                        // 发送POST请求
                        const response = await axios.post('http://1.13.163.145:8080/collection/save', formData, {
                            headers: {
                                'Content-Type': 'multipart/form-data'
                            }
                        });

                        console.log('API响应:', response.data);

                        if (response.data.code == 200) {
                            this.showMessage('信息上报成功！', 'success');

                            // 重置表单
                            this.resetForm();
                        } else {
                            this.showMessage('提交失败：' + (response.data.msg || '未知错误'), 'error');
                        }

                    } catch (error) {
                        console.error('提交失败:', error);
                        if (error.response) {
                            // 服务器返回了错误状态码
                            const errorMsg = (error.response.data && error.response.data.msg) || '服务器错误';
                            this.showMessage('提交失败：' + errorMsg, 'error');
                        } else if (error.request) {
                            // 请求已发出但没有收到响应
                            this.showMessage('网络错误，请检查网络连接', 'error');
                        } else {
                            // 其他错误
                            this.showMessage('提交失败，请重试', 'error');
                        }
                    }
                },

                // 将base64转换为Blob
                base64ToBlob(base64) {
                    const arr = base64.split(',');
                    const mime = arr[0].match(/:(.*?);/)[1];
                    const bstr = atob(arr[1]);
                    let n = bstr.length;
                    const u8arr = new Uint8Array(n);
                    while (n--) {
                        u8arr[n] = bstr.charCodeAt(n);
                    }
                    return new Blob([u8arr], {
                        type: mime
                    });
                },

                // 重置表单
                resetForm() {
                    this.formData = {
                        collectionName: '沁水县豫飞商贸有限公司',
                        marketName: '',
                        phone: '',
                        idCard: '',
                        amount: '',
                        marketPhoto: '',
                        collectionPhoto: '',
                        companyId: ''
                    };
                }
            },
            beforeDestroy() {
                // No camera stop needed as native camera app handles its own lifecycle
            }
        });
    </script>
</body>

</html>